﻿using Als.Common.String;
using log4net;
using log4net.Appender;
using System;
using System.Linq;

namespace Als.Common.File
{
    public static class LoggerHelper
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(LoggerHelper));

        #region 文本日志
        /// <summary>
        /// 常用日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="dir"></param>
        public static void LogToFile(string message, string dir = "")
        {
            WriteToFileSetting(() => Log.Info(message), "info", dir);
        }

        /// <summary>
        /// 报错日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ex"></param>
        /// <param name="dir"></param>
        public static void LogToFile(string message, Exception ex, string dir = "")
        {
            WriteToFileSetting(() => Log.Error(message, ex), "error", dir);
        }

        private static void WriteToFileSetting(Action action, string appendersName, string dir = "")
        {
            var appenders = LogManager.GetRepository().GetAppenders();
            if (!(appenders.FirstOrDefault(i => i.Name == appendersName) is RollingFileAppender appender)) return;
            appender.File = (dir.IsNullOrEmpty()
                ? "Log/{0:yyyyMMdd}/"
                : "Log/{2}/{1}/").Format(DateTime.Now, dir, appendersName);
            appender.ActivateOptions();
            action();
        }
        #endregion

    }
}
